package org.csu.sei.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.csu.sei.common.BaseConstant;
import org.csu.sei.common.ImageUpload;
import org.csu.sei.common.PageRes;
import org.csu.sei.common.ReturnJson;
import org.csu.sei.entity.DTO.MonCount;
import org.csu.sei.entity.DTO.NewsIsExistDTO;
import org.csu.sei.entity.News;
import org.csu.sei.entity.NewsContent;
import org.csu.sei.service.ICategoryService;
import org.csu.sei.service.INewsContentService;
import org.csu.sei.service.INewsService;
import org.csu.sei.service.ITeacherInfoService;
import org.csu.sei.service.impl.CategoryServiceimpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.csu.sei.common.BaseConstant.ErrorCode.*;
import static org.csu.sei.common.BaseConstant.Status.INVISIBLE;
import static org.csu.sei.common.BaseConstant.Status.VISIBLE;

//import com.sun.xml.internal.ws.handler.ClientMessageHandlerTube;
//import com.google.gson.JsonObject;

@RestController
@RequestMapping("/news")
@ResponseBody
public class NewsController implements BaseConstant{
    //需不需要加一个只获取文章标题的API

    @Resource
    private INewsService newsService;

    @Resource
    private INewsContentService newsContentService;

    @Resource
    private ICategoryService categoryService;

    @Resource
    private ITeacherInfoService teacherInfoService;

    private static final Logger logger = LoggerFactory.getLogger(NewsController.class);

    //news 和 news-content 都返回给前端
    @GetMapping("/{newsId}")
    @ResponseBody
    @ApiOperation(value = "查询文章详情接口",notes = "根据id值查询文章，其返回的json格式为{\n\"news\":{...},\n\"news_content\":{....}\n}")
    public JSONObject queryNews(@PathVariable Long newsId,@RequestHeader (value = "token",required = false)String token) {

        News news=newsService.queryNews(newsId);
        if(news==null){
            return ReturnJson.defaultFailureRes(NEWS_NOT_EXIST);
        }

        if (token == null){
            newsService.countReader(newsId);
        }

        NewsContent newsContent=newsContentService.queryNewsContent(newsId);
        JSONObject json=new JSONObject();
        json.put("news",news);
        json.put("newsContent",newsContent);
        return ReturnJson.successRes(json);
    }

    @PostMapping("")
    @ApiOperation(value = "新建文章接口",notes = "新建文章标题接口，要求前端传回news对象")
    public JSONObject insertNews(@RequestBody Map<String,JSONObject> map){
        News news = JSONObject.parseObject(map.get("news").toJSONString(),News.class) ;
        NewsContent newsContent = JSONObject.parseObject(map.get("newsContent").toJSONString(),NewsContent.class) ;
        logger.info(news.toString());
        logger.info(newsContent.toString());
        int result = newsService.insertNewsAndContent(news,newsContent);
        if(result==-5){
            return ReturnJson.defaultFailureRes(CATEGORY_IS_NOT_LEFT);
        }
        return ReturnJson.ackWithMsg("ok");
    }



    @PutMapping("/{id}")
    @ApiOperation(value = "更新文章标题简介")
    public JSONObject updateNews(@PathVariable Long id,@RequestBody Map<String,JSONObject> map){
        News news = JSONObject.parseObject(map.get("news").toJSONString(),News.class) ;
        NewsContent newsContent = JSONObject.parseObject(map.get("newsContent").toJSONString(),NewsContent.class) ;
        news.setId(id);
        newsContent.setNewsId(id);
        logger.info("news is :"+news.toString());
        logger.info("newsContent is :"+newsContent.toString());
        int result = newsService.updateNewsAndContent(news,newsContent);
        if(result<=0){
            return ReturnJson.defaultFailureRes(NEWS_NOT_EXIST);
        }
        return ReturnJson.ackWithMsg("ok");
    }



    //删除文章
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除文章接口",notes = "根据文章id值删除文章")
    public JSONObject deleteNews(@PathVariable Long id){
        newsContentService.deleteNewsContent(id);
        newsService.deleteNews(id);
        return ReturnJson.ackWithMsg("ok");
    }

    @PatchMapping("/{id}/invisible")
    @ApiOperation(value = "设置文章可见状态接口",notes = "设置可见不可见，每次请求会将其变为相反的状态")
    public JSONObject setInvisible(@PathVariable Long id){
        if(newsService.queryNews(id)==null){
            return ReturnJson.defaultFailureRes(NEWS_NOT_EXIST);
        }
        newsService.changeStatus(id);
        return ReturnJson.ackWithMsg("ok");
    }


    @GetMapping("/categoryList/{catId}")
    @ApiOperation(value = "获取相同类型的新闻接口",notes = "获取相同类型的新闻，其类型id为catId.\ncatId为6的是师资力量")
    public JSONObject querySameCategoryNews(
            @PathVariable Long catId,
            @RequestParam(value = "page",required = false,defaultValue = "0") int page,
            @RequestParam(value = "limit",required = false,defaultValue = "12") int limit,
            @RequestHeader(value = "token",required = false)String token
    ){
        PageRes pageRes;
        JSONObject json = new JSONObject();

        if(token==null){
            if(categoryService.queryCategory(catId)==null || categoryService.queryCategory(catId).getCategoryStatus()==INVISIBLE.getCode()){
                return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
            }
            if(catId==TeacherCat.TEACHER_CATEGORY_ID){
                JSONArray jsonArray = teacherInfoService.TeacherInfoList();
                json.put("staffList",jsonArray);
            }
            else{
                pageRes=newsService.querySameCategoryNews(catId,page,limit,false);
                json.put("page_res",pageRes);
            }
        }else{
            if(categoryService.queryCategory(catId)==null){
                return ReturnJson.defaultFailureRes(CATEGORY_NOT_EXIST);
            }
            if(catId==TeacherCat.TEACHER_CATEGORY_ID){
                JSONArray jsonArray = teacherInfoService.TeacherInfoList();
                json.put("staffList",jsonArray);
            }
            else{
                pageRes=newsService.querySameCategoryNews(catId,page,limit,false);
                json.put("page_res",pageRes);
            }
        }

        return ReturnJson.successRes(json);
    }

    @GetMapping("/newsList")
    @ApiOperation(value = "根据标题获取news列表")
    public JSONObject queryCategoryListByName(
            @Param("name") String name,
            @RequestParam(value = "page",required = false,defaultValue = "0") int page,
            @RequestParam(value = "limit",required = false,defaultValue = "12")int limit,
            @RequestHeader(value = "token",required = false)String token
    ){
        PageRes newsList;
        if(token == null){
            newsList=newsService.queryNewsByName(name,page,limit,false);
        }
        else{
            newsList=newsService.queryNewsByName(name,page,limit,true);
        }
        JSONObject json = new JSONObject();
        json.put("page_res",newsList);
        return ReturnJson.successRes(json);
    }

    @GetMapping("/latest")
    @ApiOperation(value = "获取最新更新的文章")
    public JSONObject queryLatestNews(
            @RequestParam(value = "page",required = false,defaultValue = "0") int page,
            @RequestParam(value = "limit",required = false,defaultValue = "12")int limit,
            @RequestHeader(value = "token",required = false)String token
    ){
        JSONObject jsonObject;
        if(token==null){
            jsonObject=newsService.queryLatestNews(page,limit,false);
        }
        else{
            jsonObject=newsService.queryLatestNews(page,limit,true);
        }
        return ReturnJson.successRes(jsonObject);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传图片至OSS服务器并返回图片的链接地址")
    public JSONObject uploadImage(@RequestParam("image_upload")MultipartFile[] imageUpload){
        JSONObject json = new JSONObject();
        try{
            JSONArray array = new JSONArray();
            for (int i=0 ; i< imageUpload.length ; ++i) {
                String url= ImageUpload.getUrl(BaseConstant.OSSConfig.NEWS_DIR,imageUpload[i]);
                array.add(url);
            }
            json.put("image_url",array);
            return ReturnJson.successRes(json);
        }
        catch (Exception e){
            return ReturnJson.defaultFailureRes(IMAGE_UPLOAD_OSS_ERROR);
        }
    }

    @DeleteMapping("/deletSome")
    public JSONObject deleteSome(@RequestBody List<Long> idList){
        JSONObject data = new JSONObject();
        boolean stat =  true;
        int count = 0;
        try {
            newsService.deleteSome(idList);
        }catch (Exception e){
            stat = false;
        }
        data.put("count",count);
        data.put("stat",stat);
        return ReturnJson.successRes(data);
    }

    @PatchMapping("/setVisible")
    public JSONObject setVisible(@RequestBody List<Long> idList){
        int count = newsService.setLook(idList,VISIBLE.getCode());
        return ReturnJson.ackWithMsg("ok");
    }

    @PatchMapping("/setDisvisible")
    public JSONObject setDisvisible(@RequestBody List<Long> idList){
        int count = newsService.setLook(idList,INVISIBLE.getCode());
        return ReturnJson.ackWithMsg("ok");
    }
    @GetMapping("/condition")
    public JSONObject multipleConditionQuery(
            @RequestParam(value = "page",required = false,defaultValue = "0") int page,
            @RequestParam(value = "limit",required = false,defaultValue = "12")int limit,
            @RequestParam(value = "catIdList",required = false)List<Long> catId,
            @RequestParam(value = "title",required = false)String name,
            @RequestParam(value = "status",required = false)List<Integer> status,
            @RequestParam(value = "id",required = false)Long id
            ){

        //logger.info(String.format( "参数 ：catId:%s ,name%s,status&s,id%s",catId!=null?catId.toString():"null",name!=null?name:"",status!=null?status.toString(),id));
        logger.info(JSON.toJSONString(catId));
        PageRes newsList= newsService.queryNewsListBySomeCondition(page, limit, catId, name,status,id);
        JSONObject json = new JSONObject();
        json.put("page_res",newsList);
        return ReturnJson.successRes(json);
    }

    @PatchMapping("/{id}/order")
    public JSONObject changeOrder(@PathVariable Long id,@RequestParam("order")int order){
        int result = newsService.changeOrder(id,order);
        if(result==-1){
            return ReturnJson.defaultFailureRes(NEWS_NOT_EXIST);
        }
        else if (result==-2){
            return ReturnJson.defaultFailureRes(NEWS_ORDER_LESS_THAN_ZERO);
        }
        return ReturnJson.ackWithMsg("ok");
    }

    @GetMapping("/{id}/information")
    public JSONObject checkNews(@PathVariable Long id)
    {
        News news = newsService.queryNews(id);
        JSONObject json = new JSONObject();
        if(news == null){
            json.put("result","news not exist");
        }
        else{
            String cateName=categoryService.queryCategory(news.getCatId()).getName();
            NewsIsExistDTO newsIsExistDTO=NewsIsExistDTO.returnNewsIsExistDTO(news,cateName);
            json.put("newsInfo", newsIsExistDTO);
        }
        return ReturnJson.successRes(json);
    }


}
